﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MetaSharp.Transformation.Patterns
{
    class VariablePattern : Pattern
    {
        public string Name { get; private set; }
        public Pattern Pattern { get; private set; }
        public VariablePattern(string name, Pattern pattern)
            : base(PatternKind.Variable)
        {
            this.Name = name;
            this.Pattern = pattern;
        }

        public override PatternMatch Compile()
        {
            var p = Pattern.Compile();
            return s => Target(s, Name, p);
        }

        private static async Task<IMatch> Target(IScope scope, string name, PatternMatch pattern)
        {
            var match = await pattern(scope);
            if (match.Matched)
                match = match.AddVariable(name, match.Value);

            return match;
        }
    }
}
